﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using System.Drawing.Printing;

using UploadManager;
//using StoreClientModuleEx;
//using StoreClientModule;
using UnityCore;

namespace MBBStoreClient
{
    public partial class frmInventoryViewer : Form
    {

        DataTable exportWholeStock = new DataTable();
        DataTable exportRetailStock = new DataTable();
        DataTable exportPriceList = new DataTable();

        SynchronizeData sync = new SynchronizeData();
        Threader t = new Threader();
        readDetails path = new readDetails();
        readDetails pLD = new readDetails();
        priceDetails pD = new priceDetails();

        string lastSearch = "";
        int cPage = 0;
        int cRes = 50;
        public frmInventoryViewer()
        {
            InitializeComponent();

            btnClose.Click += new EventHandler(btnClose_Click);
            panel2.EnabledChanged += new EventHandler(panel2_EnabledChanged);

            btnSearch.Click += new EventHandler(SearchProduct);
            txtSearch.KeyPress += new KeyPressEventHandler(txtSearch_KeyPress);
            btnPrint.Click += new EventHandler(btnPrint_Click);

            sync.ProcessCompleted += new UnityCore.CoreHandler(sync_ProcessCompleted);
            sync.ProcessError += new UnityCore.CoreHandler(sync_ProcessError);
        }

        void sync_ProcessError(string pcode, string msg)
        {
            t.SafeCall(this, delegate
            {
                MessageBox.Show(msg);
            });
        }

        void sync_ProcessCompleted(string pcode, string msg)
        {
            t.SafeCall(this, delegate
            {
                switch (pcode)
                {
                    case "GetStores":
                        cmbStore.Items.AddRange(sync.stores);
                        break;
                    case "ReadMany":
                        exportWholeStock = sync.exportTables[0];
                        exportRetailStock = sync.exportTables[1];

                        pLD.remNode = "mbb_warehouse";
                        pLD.fileName = "tblproducts";
                        pLD.date = "";

                        sync.Auto(pLD);

                        
                        break;
                    case "Auto":
                        exportPriceList = sync.export;

                        pD.tables.Add(exportWholeStock);
                        pD.tables.Add(exportRetailStock);
                        pD.tables.Add(exportPriceList);
                        pD.txtSearch = txtSearch.Text;
                        sync.extractStock(pD);

                        
                        break;
                    case "ExtractInventoryList":
                        
                        grdResult.DataSource = sync.pPriceList;
                        double whole=0, retail=0, price=0, amount = 0, qty=0;
                        grdResult.Columns["Content"].Visible = false;
                        for (int i = 0; i < grdResult.Rows.Count; i++)
                        {
                            retail = 0;
                            qty = 0;
                            whole = 0;
                            price = 0;
                            bool resultPrice, resultWhole;
                            if (!grdResult.Rows[i].Cells["PCode"].Value.ToString().Equals(""))
                            {
                                resultPrice = double.TryParse(grdResult.Rows[i].Cells["PCode"].Value.ToString(), out price);
                                if (resultPrice == false)
                                    price = 0;
                            }
                            else
                                price = 0;

                            grdResult.Rows[i].Cells["PCode"].Value = Common.FormatEquivalent(grdResult.Rows[i].Cells["PCode"].Value.ToString());
                            if (!grdResult.Rows[i].Cells["Stock"].Value.ToString().Equals(""))
                            {
                                resultWhole = double.TryParse(grdResult.Rows[i].Cells["Stock"].Value.ToString(), out whole);
                                if (resultWhole == false)
                                    whole = 0;
                            }
                            else
                                whole = 0;
                            string c = "";
                            /*if (!grdResult.Rows[i].Cells["Stock Retail"].Value.ToString().Equals(""))
                            {
                                r = grdResult.Rows[i].Cells["Stock Retail"].Value.ToString().Split(' ');
                                if (r[0].Equals(""))
                                    r[0] = "0";
                                retail = double.Parse(r[0]);
                            }*/
                            if (!grdResult.Rows[i].Cells["Content"].Value.ToString().Equals(""))
                            {
                                c = grdResult.Rows[i].Cells["Content"].Value.ToString();
                                if (c.Equals(""))
                                    c = "0";
                                qty = double.Parse(c);
                            }
                            amount = (price * whole) ;
                            if (price <= 0)
                                amount = 0.0;
                            
                            grdResult.Rows[i].Cells["Amount"].Value = Common.FormatCurrency(amount);
                        }
                        double grandTotal = 0;

                        for (int i = 0; i < grdResult.Rows.Count; i++)
                        {
                            double total =0;
                            string val = grdResult.Rows[i].Cells["Amount"].Value.ToString();
                            if (val.Equals("")) val = "0";
                            bool resultTotal = double.TryParse(val, out total);
                            if (resultTotal == false)
                                total = 0;
                            grandTotal += total;
                        }
                        lblGrandTotal.Text = Common.FormatCurrency(grandTotal);
                        lblSearchResult.Text = "Search Result: " + grdResult.Rows.Count;
                        grdResult.Columns[2].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
                        grdResult.Columns[3].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
                        grdResult.Columns[4].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
                        grdResult.Columns[5].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
                        grdResult.Columns[3].Width = 200;
                        pnlMsg.Visible = false;
                        grdResult.Sort(grdResult.Columns["Supplier"], ListSortDirection.Ascending);
                        break;

                }

            });
        }

       
        void btnPrint_Click(object sender, EventArgs e)
        {
            if (grdResult.Rows.Count > 0)
            {
                PrintInventory();
            }
        }

        void txtSearch_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)13)
            {
                SearchProduct(sender, e);
            }
        }

        void btnNext_Click(object sender, EventArgs e)
        {
        //    ControlState(false);
        //    cPage++;
        //    GenericSearchType gst = new GenericSearchType() { Keyword = lastSearch, PageNum = cPage, Qty = cRes };
        //    sm.SearchProduct(gst);
        }

        void btnPrev_Click(object sender, EventArgs e)
        {
         //   ControlState(false);
         //   cPage--;
         //   GenericSearchType gst = new GenericSearchType() { Keyword = lastSearch, PageNum = cPage, Qty = cRes };
         //   sm.SearchProduct(gst);
        }

        void SearchProduct(object sender, EventArgs e)
        {
            if (cmbStore.Text != "")
            {
                //ControlState(false);
                //lastSearch = txtSearch.Text;
                path.date = "";
                path.remNode = cmbStore.Text;
                path.fileNames.Clear();
                path.fileNames.Add("Product Stock Whole");
                path.fileNames.Add("Product Stock Retail");
                //path.fileNames.Add("tblproducts");
                sync.ReadMany(path);
                pnlMsg.Visible = true;
            }
            //cPage = 1;
            //GenericSearchType gst = new GenericSearchType(){Keyword = lastSearch, PageNum = cPage, Qty = cRes};
            //sm.GetStockInfoForPrinting(lastSearch);
        }

        void ControlState(bool state)
        {
            txtSearch.Enabled = state;
            grdResult.Enabled = state;
            btnSearch.Enabled = state;
            pnlNav.Enabled = state;
            if (!state)
            {
                pnlMsg.Visible = true;
            }
            else
            {
                pnlMsg.Visible = false;
            }
        }

        void panel2_EnabledChanged(object sender, EventArgs e)
        {
            if (!panel2.Enabled)
            {
                panel2.BackColor = Color.MidnightBlue;
            }
            else
            {
                panel2.BackColor = Color.RoyalBlue;
            }
        }
        void btnClose_Click(object sender, EventArgs e)
        {
            pnlForm.Dispose();
            this.Dispose();
        }
        public Panel PanelForm
        {
            get { return pnlForm; }
        }
        public void Initialize(string Title)
        {
            this.Select();
            lblText.Text = Title;
            sync.Stores();
            
            path.fileNames = new List<string>();
            pD.tables = new List<DataTable>();
        }

        //---------------------------------------//
        //      Printing Method                  //
        //---------------------------------------//
        int pp = 1;
        int cnt = 0;

        void PrintInventory()
        {
            PrintDocument pd = new PrintDocument();
            pd.DocumentName = lblText.Text;
            pd.PrintPage += new PrintPageEventHandler(pd_PrintPage);
            PrintDialog pdlg = new PrintDialog();
            pdlg.Document = pd;
            if (pdlg.ShowDialog() == DialogResult.OK)
            {
                PrintPreviewDialog ppdlg = new PrintPreviewDialog();
                ppdlg.Document = pd;
                //Tracking.EnterLog("Printed Inventory" + txtDR.Text, DateTime.Now.ToString());
                ppdlg.ShowDialog();
            }
        }

        void pd_PrintPage(object sender, PrintPageEventArgs e)
        {
            float lpp = 0;
            float y = 0;
            float tm = e.MarginBounds.Top;
            float lm = e.PageBounds.Left + 50;
            float lw = e.PageBounds.Width - 50;
            float th = e.PageBounds.Height - 100;
            float tHt = 0;
            Font cFont;
            StringFormat sf = new StringFormat();
            
            float rm = e.PageBounds.Width - 100;
            float bm = e.PageBounds.Height - 100;
            float ht = 0;
            float tmpStx = 0;
            float subtot = 0.0f;
            //Title
            cFont = new Font("Arial", 16f, FontStyle.Bold);
            tHt = cFont.GetHeight(e.Graphics);
            y = 50;
            sf.Alignment = StringAlignment.Center;
            e.Graphics.DrawString("MBB ROYALE INT'L INC.", cFont, Brushes.Black, (lw + 100) / 2, y, sf);
            //SubTitle
            y += tHt;
            cFont = new Font("Arial", 12f, FontStyle.Regular);
            tHt = cFont.GetHeight(e.Graphics);
            e.Graphics.DrawString("INVENTORY", cFont, Brushes.Black, (lw + 100) / 2, y, sf);

            y += tHt;
            cFont = new Font("Arial", 10f, FontStyle.Regular);
            tHt = cFont.GetHeight(e.Graphics);
            e.Graphics.DrawString("STORE NAME: "+cmbStore.Text, cFont, Brushes.Black, (lw + 100) / 2, y, sf);
            //Line
            y += tHt;
            y += tHt;
            e.Graphics.DrawLine(new Pen(Color.Black), new PointF(lm, y), new PointF(lw, y));
            //First Line

            cFont = new Font("Arial Narrow", 10f, FontStyle.Bold);
            //Table Columns
            y += (tHt * 2);
            e.Graphics.DrawString("Barcode", cFont, Brushes.Black, lm + 5, y, new StringFormat());
            e.Graphics.DrawString("Supplier", cFont, Brushes.Black, lm + 110, y, new StringFormat());
            e.Graphics.DrawString("Description", cFont, Brushes.Black, lm + 220, y, new StringFormat());
            e.Graphics.DrawString("Stock", cFont, Brushes.Black, lm + 505, y, new StringFormat());
            e.Graphics.DrawString("P. Code", cFont, Brushes.Black, lm + 580, y, new StringFormat());
            e.Graphics.DrawString("Amount", cFont, Brushes.Black, lm + 670, y, new StringFormat());
            
            e.Graphics.DrawLine(new Pen(Color.Black), new PointF(lm, y - (tHt / 2)), new PointF(lw, y - (tHt / 2)));
            e.Graphics.DrawLine(new Pen(Color.Black), new PointF(lm, y + tHt), new PointF(lw, y + tHt));
            e.Graphics.DrawLine(new Pen(Color.Black), new PointF(lm, y - (tHt / 2)), new PointF(lm, y + tHt));
            e.Graphics.DrawLine(new Pen(Color.Black), new PointF(lw, y - (tHt / 2)), new PointF(lw, y + tHt));
            
            e.Graphics.DrawLine(new Pen(Color.Black), new PointF(lm + 105, y - (tHt / 2)), new PointF(lm + 105, y + tHt));
            e.Graphics.DrawLine(new Pen(Color.Black), new PointF(lm + 215, y - (tHt / 2)), new PointF(lm + 215, y + tHt));
            e.Graphics.DrawLine(new Pen(Color.Black), new PointF(lm + 500, y - (tHt / 2)), new PointF(lm + 500, y + tHt));
            e.Graphics.DrawLine(new Pen(Color.Black), new PointF(lm + 575, y - (tHt / 2)), new PointF(lm + 575, y + tHt));
            e.Graphics.DrawLine(new Pen(Color.Black), new PointF(lm + 665, y - (tHt / 2)), new PointF(lm + 665, y + tHt));
                        
            //Table
            y += (tHt * 1.5f);
            cFont = new Font("Arial Narrow", 11f, FontStyle.Regular);
            ht = cFont.GetHeight(e.Graphics);
            tHt = ht = cFont.GetHeight(e.Graphics);
            lpp = (bm - y) / ht;
            int cl = 0;
            float stx = 0;
            cFont = new Font("Arial Narrow", 9f, FontStyle.Regular);
            while (cl <= lpp && cnt < grdResult.Rows.Count)
            {
                sf.Alignment = StringAlignment.Near;
                stx = lm + 1;

                string str = grdResult.Rows[cnt].Cells[0].Value.ToString();
                if (str.Length > 15)
                    str = str.Substring(0, 12) + "...";
                e.Graphics.DrawString(str, cFont, Brushes.Black, stx, y, sf);

                str = grdResult.Rows[cnt].Cells[1].Value.ToString();
                if (str.Length > 15)
                    str = str.Substring(0, 12) + "...";
                stx += 105;
                e.Graphics.DrawString(str, cFont, Brushes.Black, stx, y, sf);
                
                stx += 120;
                str = grdResult.Rows[cnt].Cells[2].Value.ToString();
                if (str.Length > 40)
                    str = str.Substring(0, 37) + "...";
                e.Graphics.DrawString(str, cFont, Brushes.Black, stx, y, sf);

                sf.Alignment = StringAlignment.Far;
                stx += 335;
                str = grdResult.Rows[cnt].Cells[3].Value.ToString();
                e.Graphics.DrawString(str, cFont, Brushes.Black, stx, y, sf);

                stx += 90;
                str = grdResult.Rows[cnt].Cells[4].Value.ToString();
                e.Graphics.DrawString(str, cFont, Brushes.Black, stx, y, sf);

                stx += 90;
                str = grdResult.Rows[cnt].Cells[5].Value.ToString();
                e.Graphics.DrawString(str, cFont, Brushes.Black, stx, y, sf);
                subtot += float.Parse(grdResult.Rows[cnt].Cells[5].Value.ToString());
                e.Graphics.DrawLine(new Pen(Color.Black), new PointF(lm, y + tHt), new PointF(lw, y + tHt));
                e.Graphics.DrawLine(new Pen(Color.Black), new PointF(lm, y - (tHt / 2)), new PointF(lm, y + tHt));
                e.Graphics.DrawLine(new Pen(Color.Black), new PointF(lw, y - (tHt / 2)), new PointF(lw, y + tHt));

                e.Graphics.DrawLine(new Pen(Color.Black), new PointF(lm + 105, y - (tHt / 2)), new PointF(lm + 105, y + tHt));
                e.Graphics.DrawLine(new Pen(Color.Black), new PointF(lm + 215, y - (tHt / 2)), new PointF(lm + 215, y + tHt));
                e.Graphics.DrawLine(new Pen(Color.Black), new PointF(lm + 500, y - (tHt / 2)), new PointF(lm + 500, y + tHt));
                e.Graphics.DrawLine(new Pen(Color.Black), new PointF(lm + 575, y - (tHt / 2)), new PointF(lm + 575, y + tHt));
                e.Graphics.DrawLine(new Pen(Color.Black), new PointF(lm + 665, y - (tHt / 2)), new PointF(lm + 665, y + tHt));
                
                y += ht;
                cnt++;
                cl++;
            }
            cFont = new Font("Arial Narrow", 9f, FontStyle.Bold);
            if (cnt < grdResult.Rows.Count)
            {
                e.Graphics.DrawString("Sub Total: " + subtot.ToString("#,#0.00"), cFont, Brushes.Black, stx, y, sf);
                e.HasMorePages = true;
                pp++;
            }
            else
            {
                e.Graphics.DrawString("Sub Total: " + subtot.ToString("#,#0.00"), cFont, Brushes.Black, stx, y, sf);
                y += ht;
                e.Graphics.DrawString("Grand Total: " + lblGrandTotal.Text, cFont, Brushes.Black, stx, y, sf);
                e.HasMorePages = false;
                cnt = 0;
                pp = 1;
            }
             
            /*
            cFont = new Font("Courier New", 12f, FontStyle.Regular);
            tHt = cFont.GetHeight(e.Graphics);
            float amt = 0f;
            for (int i = 0; i < items.Rows.Count; i++)
            {
                sf.Alignment = StringAlignment.Center;
                e.Graphics.DrawString(items.Rows[i]["Qty"].ToString(), cFont, Brushes.Black, lm + 32, y, sf);
                e.Graphics.DrawString(items.Rows[i]["Barcode"].ToString(), cFont, Brushes.Black, lm + 70, y, new StringFormat());
                string str = items.Rows[i]["Description"].ToString();
                if (str.Length > 25) str = str.Substring(0, 22) + "...";
                e.Graphics.DrawString(str, cFont, Brushes.Black, lm + 200, y, new StringFormat());
                sf.Alignment = StringAlignment.Far;
                e.Graphics.DrawString(items.Rows[i]["P.Code"].ToString(), cFont, Brushes.Black, lm + 625, y, sf);
                amt = float.Parse(items.Rows[i]["Qty"].ToString()) * float.Parse(UnitPrice.Rows[i]["UnitPrice"].ToString());
                e.Graphics.DrawString(General.FormatCurrency(amt.ToString()), cFont, Brushes.Black, lw - 5, y, sf);
                y += (tHt * 1.25f);
            }
            cFont = new Font("Courier New", 12f, FontStyle.Bold);
            tHt = cFont.GetHeight(e.Graphics);
            y = th - 200 - (tHt * 1.25f);
            e.Graphics.DrawString("TOTAL", cFont, Brushes.Black, lm + 550, y, new StringFormat());
            e.Graphics.DrawString(txtTotal.Text, cFont, Brushes.Black, lw - 5, y, sf);
            e.Graphics.DrawLine(new Pen(Color.Black), new PointF(lm, th - 200 - (tHt * 1.5f)), new PointF(lw, th - 200 - (tHt * 1.5f)));
            //Footer
            cFont = new Font("Arial", 12f, FontStyle.Regular);
            tHt = cFont.GetHeight(e.Graphics);
            y = th - 200 + 50;
            sf.Alignment = StringAlignment.Near;
            e.Graphics.DrawString("All merchandise covered by this delivery receipt has been", cFont, Brushes.Black, lm + 5, y, sf);
            e.Graphics.DrawString("Received in good order and condition", cFont, Brushes.Black, lw - 250, y, sf);

            y += tHt;
            e.Graphics.DrawString("verified and checked by receiver in good condition.", cFont, Brushes.Black, lm + 5, y, sf);
            y += tHt;
            e.Graphics.DrawString("_____________________________", cFont, Brushes.Black, lw - 250, y, sf);

            y += tHt;
            cFont = new Font("Arial", 8f, FontStyle.Bold);
            tHt = cFont.GetHeight(e.Graphics);
            e.Graphics.DrawString("AUTHORIZED SIGNATURE", cFont, Brushes.Black, lw - 190, y, sf);
            */
        }

    }
}
